package io.lkt.modules.sys.controller;

import com.google.common.collect.Lists;
import io.lkt.common.redis.RedisCacheUtil;
import io.lkt.common.util.Query;
import io.lkt.common.util.SpringContextUtil;
import io.lkt.common.utils.AliyunOssClientUtil;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.R;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.job.utils.HttpGetPostUtils;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.redis.SysConfigRedis;
import io.lkt.modules.sys.service.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping({"/sys/bmaterialinfo"})
public class BMaterialController extends AbstractController
{
    private static final Logger logger = LoggerFactory.getLogger(BMaterialController.class);
    @Autowired
    private BVideoInfoService bVideoInfoService;
    @Autowired
    private BArticleInfoService bArticleInfoService;

    @Autowired
    private BBrandInfoService bBrandInfoService;

    @Autowired
    private BArticleTypeInfoService bArticleTypeInfoService;

    @Autowired
    private BMaterialInfoService materialInfoService;

    @Autowired
    RedisCacheUtil redisCacheUtil;

    @Value("${serviceUrls}")
    private String serviceUrls;



    @RequestMapping({"/queryList"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    public R queryList(@RequestParam Map<String, Object> params) {
        System.out.println(params);
        Query query = new Query(params);
        List<BArticleInfoEntity> brandList = this.materialInfoService.queryList(query);
       // System.out.println(brandList.toString());
        for (BArticleInfoEntity bArticleInfoEntity : brandList)
        {
            if ((bArticleInfoEntity.getArticleSource() != null) && (bArticleInfoEntity.getArticleSource().intValue() == 1)) {
                bArticleInfoEntity.setUserName("管理员");
            }
            if (bArticleInfoEntity.getArticleBrandId() != null)
            {
                BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bArticleInfoEntity.getArticleBrandId());
                if (bBrandInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bBrandInfoEntity.getBrandName());
                }
            }
            if (bArticleInfoEntity.getArticleTypeId() != null)
            {
                BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bArticleInfoEntity.getArticleTypeId());
                if (bArticleTypeInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
                }
            }
        }
        int total = this.materialInfoService.queryTotal(query).intValue();
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping({"/save"})
    @RequiresPermissions({"sys:barticleinfo:save"})
    public R save(@RequestBody BArticleInfoEntity bVideoInfo) throws Exception {
        bVideoInfo.setArticleTitle("素材");
        if ((bVideoInfo.getBrandName().equals("")) && (bVideoInfo.getArticleTypeName().equals(""))) {
            return R.error("请选择品牌或分类");
        }
        bVideoInfo.setCreateTime(new Date());
        bVideoInfo.setModifyTime(new Date());
        bVideoInfo.setArticleSource(Integer.valueOf(1));
        bVideoInfo.setArticleStatus(Integer.valueOf(1));
      //  bVideoInfo.setSpiderProcessStatus(Integer.valueOf(1));
      //  bVideoInfo.setArticleVersionNum(Integer.valueOf(2));
        bVideoInfo.setSType("后台录入");
        bVideoInfo.setResourceType(Integer.valueOf(3));
        bVideoInfo.setArticleBrandId(null);
        bVideoInfo.setArticleTypeId(null);
        if (!bVideoInfo.getBrandName().equals("")) {
            String[] brandNames = bVideoInfo.getBrandName().split(",");
            if (brandNames != null) {
                for(int i = 0; i < brandNames.length; i++) {
                     BBrandInfoEntity brandInfoEntity = new BBrandInfoEntity();
                     brandInfoEntity.setId(this.bBrandInfoService.queryByName(brandNames[i]).getId());
                     if(brandInfoEntity == null){
                         return R.error("所选的品牌不存在");
                     }
                     bVideoInfo.setArticleBrandId(brandInfoEntity.getId());
                     String materialImgUrls = bVideoInfo.getArticleImgUrl();
                     bVideoInfo.setArticleImgUrl(null);
                     this.bArticleInfoService.setNullArticleTypeId(bVideoInfo.getId());
                     this.bVideoInfoService.save(bVideoInfo);
                     this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByBrandForHotValue" + brandInfoEntity.getId());
                     // 插入素材图表
                     this.materialInfoService.insertMaterialImg(bVideoInfo.getId(), materialImgUrls);
                     HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
                }
                return R.ok();
            }
            return R.error("所选的品牌不存在");
        }
        if (!bVideoInfo.getArticleTypeName().equals("")) {
            BArticleTypeInfoEntity articleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(bVideoInfo.getArticleTypeName());
            if (articleTypeInfoEntity != null) {
                String materialImgUrls = bVideoInfo.getArticleImgUrl();
                bVideoInfo.setArticleImgUrl(null);
                bVideoInfo.setArticleTypeId(articleTypeInfoEntity.getId());
                this.bArticleInfoService.setNullArticleBrandId(bVideoInfo.getId());
                this.bVideoInfoService.save(bVideoInfo);
                this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByTypeForHotValue" + articleTypeInfoEntity.getId());
                // 插入素材图表
                this.materialInfoService.insertMaterialImg(bVideoInfo.getId(),materialImgUrls);
                HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
                return R.ok();
            }
            return R.error("所选的类型不存在");
        }
        logger.info("新增视频:" + bVideoInfo.getArticleTitle());
        return R.error("新增素材失败");
    }

    @RequestMapping({"/info/{id}"})
    @RequiresPermissions({"sys:barticleinfo:info"})
    public R info(@PathVariable("id") Integer id) throws IOException {
        BArticleInfoEntity bVideoInfo = (BArticleInfoEntity)this.bVideoInfoService.getById(id);
        // 查询素材图片地址
        String materialImgUrl =this.materialInfoService.selectMaterialImgUrl(id);
        if (StringUtils.isNotBlank(materialImgUrl)){
            bVideoInfo.setArticleImgUrl(materialImgUrl);
        }
        if (bVideoInfo.getArticleBrandId() != null) {
            BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bVideoInfo.getArticleBrandId());
            if (bBrandInfoEntity != null) {
                bVideoInfo.setBrandName(bBrandInfoEntity.getBrandName());
            }
        }
        if (bVideoInfo.getArticleTypeId() != null) {
            BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bVideoInfo.getArticleTypeId());
            if (bArticleTypeInfoEntity != null) {
                bVideoInfo.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
            }
        }
        HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
        return R.ok().put("bVideoInfo", bVideoInfo);
    }

    @RequestMapping({"/updateInfo"})
    @RequiresPermissions({"sys:barticleinfo:update"})
    public R updateInfo(@RequestBody BArticleInfoEntity bVideoInfo) throws Exception {
        if ((bVideoInfo.getBrandName().equals("")) && (bVideoInfo.getArticleTypeName().equals(""))) {
            return R.error("请选择品牌或分类");
        }
        ValidatorUtils.validateEntity(bVideoInfo, new Class[0]);
        String cacheKey = bVideoInfo.getId() + "ArticleDetailInfoKey";
        if ((bVideoInfo.getArticleStatus() != null) && (bVideoInfo.getArticleStatus().intValue() == 0)) {
            bVideoInfo.setArticleStatus(Integer.valueOf(0));
            bVideoInfo.setRedisStoreStatus(Integer.valueOf(2));
        }
        Boolean redisDel = Boolean.valueOf(this.redisCacheUtil.removeSingleCacheMaster(cacheKey));
        System.out.println("***** BArticleInfoController updateInfo redisDel:" + redisDel + " _ cacheKey:" + cacheKey);
        bVideoInfo.setModifyTime(new Date());

        bVideoInfo.setArticleBrandId(null);
        bVideoInfo.setArticleTypeId(null);
        if (!bVideoInfo.getBrandName().equals("")) {
            BBrandInfoEntity brandInfoEntity = this.bBrandInfoService.queryByName(bVideoInfo.getBrandName());
            if (brandInfoEntity != null) {
                String materialImgUrls = bVideoInfo.getArticleImgUrl();
                bVideoInfo.setArticleImgUrl(null);
                bVideoInfo.setArticleBrandId(brandInfoEntity.getId());
                this.bArticleInfoService.setNullArticleTypeId(bVideoInfo.getId());
                this.bArticleInfoService.updateById(bVideoInfo);
                // 更新素材图表
                if (StringUtils.isNotBlank(materialImgUrls)){
                    Integer num = this.materialInfoService.updateMaterialImg(bVideoInfo.getId(),materialImgUrls);
                    if (num.equals(0)){
                        this.materialInfoService.insertMaterialImg(bVideoInfo.getId(),materialImgUrls);
                    }
                }
                HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
                return R.ok();
            }
            return R.error("所选的品牌不存在");
        }
        if (!bVideoInfo.getArticleTypeName().equals("")) {
            BArticleTypeInfoEntity articleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(bVideoInfo.getArticleTypeName());
            if (articleTypeInfoEntity != null)
            {
                String materialImgUrls = bVideoInfo.getArticleImgUrl();
                bVideoInfo.setArticleImgUrl(null);
                bVideoInfo.setArticleTypeId(articleTypeInfoEntity.getId());
                this.bArticleInfoService.setNullArticleBrandId(bVideoInfo.getId());
                this.bArticleInfoService.updateById(bVideoInfo);
                if (StringUtils.isNotBlank(materialImgUrls)){
                    Integer num = this.materialInfoService.updateMaterialImg(bVideoInfo.getId(),materialImgUrls);
                    if (num.equals(0)){
                        this.materialInfoService.insertMaterialImg(bVideoInfo.getId(),materialImgUrls);
                    }
                }
                HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
                return R.ok();
            }
            return R.error("所选的类型不存在");
        }
        logger.info("更新视频:" + bVideoInfo.getArticleTitle());
        return R.error("新增视频失败");
    }



}
